import os
import subprocess
from ogreEx.CReportSingleton import Report
from ogreEx.config import getConfig



class _image_processing_( object ):

    def _reformat( self, name, image ):
        if image.convert_format != 'NONE':
            name = '%s.%s' %(name[:name.rindex('.')], image.convert_format)
            if image.convert_format == 'dds': name = '_DDS_.%s' %name

        elif image.use_resize_half or image.use_resize_absolute or image.use_color_quantize or image.use_convert_format:
            name = '_magick_.%s' %name


        if getConfig()['FORCE_IMAGE_FORMAT'] != 'NONE' and not name.endswith('.dds'):
            name = '%s.%s' %(name[:name.rindex('.')], getConfig()['FORCE_IMAGE_FORMAT'])
            if getConfig()['FORCE_IMAGE_FORMAT'] == 'dds':
                name = '_DDS_.%s' %name


        return name

    def image_magick( self, texture, infile ):
        print('IMAGE MAGICK', infile )
        exe = getConfig()['IMAGE_MAGICK_CONVERT']
        if not os.path.isfile( exe ):
            Report.warnings.append( 'ImageMagick not installed!' )
            print( 'ERROR: can not find Image Magick - convert', exe ); return
        cmd = [ exe, infile ]
        ## enforce max size ##
        x,y = texture.image.size
        ax = texture.image.resize_x
        ay = texture.image.resize_y

        if texture.image.use_convert_format and texture.image.convert_format == 'jpg':
            cmd.append( '-quality' )
            cmd.append( '%s' %texture.image.jpeg_quality )

        if texture.image.use_resize_half:
            cmd.append( '-resize' )
            cmd.append( '%sx%s' %(x/2, y/2) )
        elif texture.image.use_resize_absolute and (x>ax or y>ay):
            cmd.append( '-resize' )
            cmd.append( '%sx%s' %(ax,ay) )

        elif x > getConfig()['MAX_TEXTURE_SIZE'] or y > getConfig()['MAX_TEXTURE_SIZE']:
            cmd.append( '-resize' )
            cmd.append( str(getConfig()['MAX_TEXTURE_SIZE']) )

        if texture.image.use_color_quantize:
            if texture.image.use_color_quantize_dither:
                cmd.append( '+dither' )
            cmd.append( '-colors' )
            cmd.append( str(texture.image.color_quantize) )

        path,name = os.path.split( infile )
        #if (texture.image.use_convert_format and texture.image.convert_format == 'dds') or getConfig()['FORCE_IMAGE_FORMAT'] == 'dds':
        outfile = os.path.join( path, self._reformat(name,texture.image) )
        if outfile.endswith('.dds'):
            temp = os.path.join( path, '_temp_.png' )
            cmd.append( temp )
            print( 'IMAGE MAGICK: %s' %cmd )
            subprocess.call( cmd )
            self.nvcompress( texture, temp, outfile=outfile )

        else:
            cmd.append( outfile )
            print( 'IMAGE MAGICK: %s' %cmd )
            subprocess.call( cmd )


    def nvcompress(self, texture, infile, outfile=None, version=1, fast=False, blocking=True):
        print('[NVCompress DDS Wrapper]', infile )
        assert version in (1,2,3,4,5)
        exe = getConfig()['NVCOMPRESS']
        cmd = [ exe ]

        if texture.image.use_alpha and texture.image.depth==32:
            cmd.append( '-alpha' )

        if not texture.use_mipmap:
            cmd.append( '-nomips' )

        if texture.use_normal_map:
            cmd.append( '-normal' )
            if version in (1,3):
                cmd.append( '-bc%sn' %version )
            else:
                cmd.append( '-bc%s' %version )

        else:
            cmd.append( '-bc%s' %version )

        if fast:
            cmd.append( '-fast' )
        cmd.append( infile )

        if outfile: cmd.append( outfile )

        print( cmd )
        if blocking:
            subprocess.call( cmd )
        else:
            subprocess.Popen( cmd )